<?php

namespace App\Http\Controllers\Order;

use App\Helpers\NewBaseData;
use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Miniprograme\SubscribeController;
use App\Models\CarService;
use App\Models\Order\LeaseChangeLog;
use App\Models\Order\OrderPrePay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\RecognizeDrivingLicense;

class OrderController extends Controller
{
    use ResponseData,NewBaseData,PayTrait;

    //订单列表
    public function list(CarOrder $order,Request $request){
        $phone = $request->input('phone','');
        $size = $request->input('size',10);
        $page = $request->page-1;

        $data = $order->with('car','user')
            ->when($phone,function($query)use($phone){
                $query->where('phone',$phone);
            })
            ->orderByDesc('id')
            ->get();
        $others = $order->with('car','user')
            ->when($phone,function($query)use($phone){
                $query->where('phone',$phone);
            })
            //->whereIn('status',[-1,7,8])
            ->orderByDesc('id')
            ->get();
        if($others) {
            foreach ($others as $item) {
                $data->push($item);
            }
        }

        $slice = $data->slice($page*$size, $size);
        $res['current_page'] = $page+1;
        $res['total'] = $data->count();
        $last =  array();
        foreach ($slice as $value){
            $last[] = $value;
        }
        $res['data'] = $last;
        return $this->success($res);
    }
    public function update(Request $request){
        $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
        if($order){
            if($request->status==6&&!$request->filled('return_position')){
                return $this->failed('请选择还车地址',201);
            }
            if($request->status==-4&&$order->status==2){
                $total = $order->mini_pay*100;
                if($order->mini_pay<$order->total){
                    $res = $this->miniRefund($order->order_sn,$order->out_trade_no,$total,$total);
                    Log::info(json_encode($res));
                    return $this->success('退款成功!');
                }else{
                    return $this->failed('退款失败,请联系管理员',201);
                }

            }
            if($request->status==-4&&$order->status>2){
                return $this->failed('已经进入送车状态，请联系管理员退款',201);
            }

            $map = $this->chooseStatus($request,$order);
            $order->update($map);
            return $this->success('修改成功');

        }else{
            return $this->failed('订单不存在',201);
        }

    }
    protected function isSetCar($id){
        return CarOrder::query()->find($id);
    }
    public function chooseStatus($request,$data){

        $map = $request->all();
        switch ($request->status)
        {
            case 2:
                $map['send_car_time'] = now();
                (new SubscribeController())->send_template($data);
                break;
            case 3:
                $map['fetch_time'] = now();
                (new SubscribeController())->send_arrive($data);
                break;
            case -1:
                if($data->status==0){
                    $map['status']= -1;
                }
                //$result = $this->refund($data);
                $map['updated_at'] = now();
                break;
            case -4:
                $map['status']= -4;
                $this->refund($data);
                break;
            case 6:
                $map['return_time'] = now();
                $this->diffDays($data->pre_fetch_time,now());
                $map['lease_days'] = $this->daily;
                $map['fetch_hours'] = $this->hours;
                $map['return_position'] = $request->return_position?:null;
                $map['status'] = 6;
                //释放车辆
                // RecognizeDrivingLicense::query()
                //     ->where('id',$data->gear_car_id)
                //     ->update(['is_used'=>0]);
                break;
        }
        return $map;
    }
    //小程序接口
    public function all(Request  $request){
        $size = $request->input('size',10);
        if($request->status==7){
            $data = CarOrder::where('openid',$request->openid)
//                ->whereNotIn()
                ->orderBy('id','desc')->simplePaginate($size);
        }else{
            $data = CarOrder::where('openid',$request->openid)->where('status',$request->status)->orderBy('id','desc')->simplePaginate($size);
        }
        return $this->success($data);

    }
    public function orderDetail(Request $request){
        $data = CarOrder::with('service','car','user','contracts')->find($request->id);
        return $this->success($data);
    }
    public function orderDetailById(Request $request){
        $data = CarOrder::query()->with('customer')->where('id',$request->id)->first();
        return $this->success($data);
    }
    //订单退款
    public function refund($order){
        $data = [
            'type' => 'miniapp',
            'out_trade_no' => $order->out_trade_no,
            'out_refund_no' => time(),
            'total_fee' => $order->bc_total*100,
            'refund_fee' => $order->bc_total*100,
            'refund_desc' => '全额退款',
            'notify_url' => 'https://zc.ywbtzc.com/api/pay/refund',
        ];
        $result = $this->WxPay()->refund($data);
        return $result;
    }
    public $order;
    public function testTemplate(){
        $this->order = 'o7sQR5bADtCkqEaGf7-J84Wz51Yw';
//        return $this->success($this->order);
        (new SubscribeController())->send_arrive($this->order,'接单通知');
    }
    // 获取订单分总台记录
    public function orderChangeLog(LeaseChangeLog $model, Request $request){
        $size = $request->input('size',10);
        $data = $model->query()->paginate($size);
        return $this->success($data);
    }
    // 预付信息
    public function prepaidInformation(Request $request){
        $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
        if(!$request->filled('order_sn')){
            return $this->failed('订单号不存在',201);
        }
        $data['order_sn'] = $request->order_sn;
        $data['cost_total'] = $request->cost_total;
        $data['cost_diff'] = $request->cost_diff;
        $data['break_rules'] = $request->break_rules;
        $data['break_rules_status'] = $request->break_rules_status;
        $data['deposit'] = $request->deposit;
        $data['deposit_status'] = $request->deposit_status;
        $data['pay_back'] = $request->pay_back;
        $data['server_info'] = $request->server_info;
        $data['attend_info'] = $request->attend_info;
        $data['payd_deposit'] = $request->payd_deposit;
        // 修改预付，不需要修改订单的金额了
        // 如果是第一次修改预付信息，则记录当前订单金额保存起来，下次使用
        // if (!$request->filled('id')) {
        //     $order->bc_total_before = $order->bc_total;
        //     $fact_total = $order->bc_total+$request->pay_back;
        // } else {
        //     $fact_total = $order->bc_total_before+$request->pay_back;
        // }
        $fact_total = $order->bc_total+$request->pay_back;
        if($fact_total<=0){
            return $this->failed('应补预付不能小于订单金额',201);
        }
        OrderPrePay::query()->updateOrCreate(['id'=>$request->id],$data);
        // $order->bc_total = round($fact_total, 2);
        // $order->save();
        return $this->success('更新成功');

    }
}
